package scaladuct.l10n

import java.lang.String
import java.util.{MissingResourceException, Enumeration, ResourceBundle, Locale}

/**
 * <p>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Dec 12, 2010
 * Time: 9:37:57 PM
 */

@serializable @SerialVersionUID(1L)
trait AbstractL10nProperties extends L10nProperties {
  val bundlePrefix: String
  val bundleName: String

  def bundle(locale: Locale) = try {
    Some(loadBundle(locale))
  } catch {
    case mre: MissingResourceException => {
      //NullBundle
      None
    }
  }

  protected def loadBundle(locale: Locale): ResourceBundle =
    if (bundlePrefix == null || bundlePrefix == "")
      ResourceBundle.getBundle(bundleName, locale)
    else
      new PrefixedBundle(ResourceBundle.getBundle(bundleName, locale))

  class PrefixedBundle(val wrapped: ResourceBundle) extends ResourceBundle {
    def getKeys(): Enumeration[String] = {
      val keys = wrapped.getKeys
      new Enumeration[String] {
        def nextElement: String = {
          keys.nextElement.substring(bundlePrefix.length)
        }

        def hasMoreElements = keys.hasMoreElements
      }
    }

    def handleGetObject(key: String): AnyRef = {
      val value = wrapped.getObject(bundlePrefix + key)
      value
    }
  }


  object NullBundle extends ResourceBundle {
    def getKeys = new Enumeration[String] {
      def nextElement = throw new NoSuchElementException

      def hasMoreElements = false
    }

    def handleGetObject(key: String) = null
  }
}